<template>
  <div v-swiperight="swipeRight" class="wrapp_content" :style="bgStyle">
    <loading :show="initLoading && !identityControll" />
    <!-- <outer-pop v-if="!serverUa.isJeTiao && !identityControll" /> -->
    <atmosphere v-if="pageContent.atmosphere" class="innerAt" />
    <header-bar-module
      v-if="serverUa.isJeTiao && !noNav"
      :activity-code="activityCode"
      :redirect-u-r-l="backRedirectURL"
      :scroll-height="scrollTopHeight"
    />
    <div>
      <div v-if="pageTop && !noNav" class="head-padding-top"></div>
      <div
        v-if="authTag || (!authTag && !pageContent.unauthImage)"
      >
        <div
          v-for="item in componentList"
          :id="item._id"
          :key="item._id+keyRenderId"
          :class="item.code"
        >
          <component
            :is="item.code"
            v-if="item.ruleVisible"
            :rule-contents="item.ruleContents"
            :component-id="item._id"
            :activity-code="activityCode"
          />
        </div>
      </div>
      <img
        v-if="
          !authTag &&
            pageContent.unauthImage &&
            !showError &&
            activityInfo.activityStatus === 0
        "
        style="width: 100%"
        :src="pageContent.unauthImage"
        @click="unAuthImageClik"
      />
      <transition name="fade">
        <img
          v-show="isShowStick"
          id="stick_btn"
          class="stick_btn"
          src="../../assets/image/stick.png"
          @click="scrollToTop"
        />
      </transition>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'
import tool from '@/util/tool'
import ua from '@/util/ua'
import { Toast, Overlay } from 'vant'
import { get } from '@/servers/apihttp'
import smoothscroll from 'smoothscroll-polyfill'
import { componentStack } from '@/util/biz/componentStack'
import OuterPop from '@/components/OuterPop'
import Loading from '@/components/Loading'
import { SELF_RULE_FILTER_COMPONENTS } from '@/util/biz/dic'
import indexMixin from './Mixin/index'
import leaveMixin from './Mixin/leave'
import device from '@/util/device'
import '@/util/touch'
export default {
  components: {
    [Toast.name]: Toast,
    ...componentStack,
    OuterPop,
    Overlay,
    Loading
  },
  mixins:[indexMixin,leaveMixin],
  provide () {
    return {
      backFromLogin: () => this.authTag
    }
  },
  async asyncData({ store }) {
    return {
      activityInfo:store.state.main.pageContent,
      authTag:store.state.server.userNo?true:false,
      unAuthComponentList:JSON.parse(JSON.stringify(store.state.main.pageContent.componentList))
    }
  },
  data () {
    return {
      backRedirectURL: null,
      initLoading: true,
      showError: false,
      preview: null,
      activityInfo: {},
      isShowStick: false,
      scrollTopHeight: 0,
      redirectClock: null,
      authTag: false,
      loadCount: 0,
      unAuthComponentList: [],
      keyRenderId:new Date().getTime(),
      deviceH:1080
    }
  },
  head(){
    return {
      title:this.activityInfo.title
    }
  },
  computed: {
    ...mapGetters('main', ['pageContent','swipeBackTag']),
    ...mapGetters('server', ['serverUa','activityCode','userNo','versionRule']),
    componentList(){
      if (!this.authTag && this.pageContent.unauthImage) return []
      let list=this.activityInfo.componentList.filter(a => a.type !== 'hidden' )
      return list
    },
    noNav(){
      // return this.pageContent.noNav
      let head = tool.getUrlParam('headerBar')
      if (head && head==='hide'){
        return true
      } else {
        return false
      }
    },
    identityControll () {
      return tool.getUrlParam('d') ? true : false
    },
    isNative () {
      return tool.IS_NATIVE()
    },
    isServer(){
      return process.server
    },
    pageTop () {
      let isJeTiao=process.client?ua.isJeTiao:this.serverUa.isJeTiao
      let f1 = !this.pageContent.headerStyle || this.pageContent.headerStyle === 1
      return f1 && isJeTiao
    },
    bgStyle(){
      let content = this.pageContent
      if (this.pageContent.background) {
        content = this.pageContent.background
      }
      if (!content.bgStartColor || !content.bgEndColor) return null
      let bgMidColor = content.bgMidColor
        ? content.bgMidColor
        : content.bgEndColor
      let bgStartPosition =  content.bgStartPosition? content.bgStartPosition:0 
      let bgMidPosition =
          content.bgMidPosition === null
            ? 50
            : content.bgMidPosition
      let bgEndPosition =
          content.bgEndPosition === null
            ? 100
            : content.bgEndPosition
      let unit = content.bgType === 2 ? 'px' : '%'
      let bgText = `linear-gradient(${content.bgStartColor} ${bgStartPosition + unit
      },${bgMidColor} ${bgMidPosition + unit},${content.bgEndColor
      } ${bgEndPosition + unit})`
      return {
        background:bgText,
        backgroundSize:'100% 100%',
        backgroundRepeat: 'no-repeat',
        minHeight:this.deviceH+'px'
      }
    }
  },
  created () {
    if (process.client){
      this.deviceH=window.screen.height
    }
    this.preview = tool.getUrlParam('type')
  },
  async mounted  ()  {
    // 关闭侧滑返回
    if (tool.IS_NATIVE()){ 
      // window.App.gestureAble({ able: 'N', wkWebViewAble: 'Y' })
    }
    setTimeout(() => {
      console.log('900毫秒兜底，去掉loading')
      this.initLoading=false
    },900)
    if (this.pageContent.activityStatus!==0) {
      this.$router.push({ path: '/mobile/activityEnd', params: { activityCode: this.activityCode } })
      return
    }
    if (!this.versionRule.iosApp && !this.versionRule.androidApp && tool.IS_NATIVE()){
      // 外链跳转进入的APP，需要调用jssdk获取版本参数存到store
      let info = await device.getRuleDeviceParams()
      this.setVersionRule(info)
    }
    console.log(location.href)
    console.log(window.screen.width,window.screen.height,window.devicePixelRatio)
    this.ddRedirect()
    if (!this.userNo){
      await this.clientPageRender()
    } else {
      this.initLoading=false
    }
    this.savePvData()
    smoothscroll.polyfill()
    this.$sendQdas('8888110101', {
      item_name: '宜搭H5'
    })
    this.$nextTick(() => {
      // 处理置顶按钮
      window.addEventListener('scroll', this.scroll)
      this.initAndriodBack()
      if (this.pageContent.showCouponPop){
        this.loadRetainPopCoupon()
      }
    }) 
  },
  methods: {
    ...mapMutations('main', ['setPageContent', 'editComponent','addComponent','setQueryRuleTag','setComponentVisible','hideComponents','setComponentRuleContens','editPage']),
    ...mapMutations('server', ['setUserNo','setVersionRule']),
    swipeRight(){
      if (!this.swipeBackTag){
        return
      }
      console.log('侧滑返回')
      if (this.pageContent.showCouponPop && this.userNo){
        
        this.handleLeavePage()
      } else {
        console.log('App返回')
        // window.App.back()
      }
    },
    changeRuleVisible (componentId, tag) {
      this.editComponent({
        _id: componentId,
        field: 'ruleVisible',
        value: tag,
      })
    },
    changeRuleContents (componentId, arr) {
      this.editComponent({
        _id: componentId,
        field: 'ruleContents',
        value: arr,
      })
    },
    async loadPageJson () {
      this.showError = false
      let activityCode = tool.getUrlParam('activityCode')
      let type = tool.getUrlParam('type')
      
      let  response = ''
      if (type && type==='preview'){
        let rep =await this.$axios.post('/activity/getActivityJsonInfo',{ activityCode:activityCode } )
        response=rep.data
      } else {
        let url=tool.getPageJsonUrl(activityCode)
        response = await get(url).catch((e) => {
          console.log(e.message)
          this.showError = true
        }) 
      }
      let mouse=response.componentList.find(a => a.code==='BeatMouseModule')
      let queryData={ 
        activityCode:activityCode,
        gameNo:(mouse?mouse.gameNo:'') 
      }
      let activity =await this.$axios.post('/activity/queryActivityIsStarted',queryData )
      if (activity && activity.flag==='S'){
        response.activityStatus=activity.data.activityStatus
        if (mouse){ mouse.gameStatus=activity.data.gameStatus } 
      }
      this.keyRenderId=new Date().getTime()
      response.clientRender=true
      this.setPageContent(response)
      this.activityInfo=response
      await this.getNeedRuleFilter()
      setTimeout(() => {
        console.log('150毫秒后去掉loading')
        this.initLoading=false
      },150)
    },
    async getNeedRuleFilter () {
      let ruleQueryList = []
      // 将ruleButton转化成普通组件，以便统一处理人群
      let tmp = this.activityInfo?.ruleButton
      let ruleButton={ 
        _id:'rule-' + this.activityCode,
        code:'ruleButton',
        type:'hidden'
      }
      if (tmp){
        ruleButton={ ...ruleButton,...tmp }
      }
      this.addComponent(ruleButton)
      let list=this.activityInfo.componentList
      // 只能用for循环，await在foreach中不起效
      for (let i=0;i<list.length;i++){
        let element=list[i]
        let id = this.dealComponentRule(element)
        if (id) {
        // 组件设置了人群规则(此标记通知组件内部业务接口，需要人群过滤)
          this.setQueryRuleTag({ id:element._id,tag:true })
          if (!SELF_RULE_FILTER_COMPONENTS.includes(element.code)){
          // 简单组件
            ruleQueryList.push(id)
          } else {
          // 自处理规则的业务组件
            this.setComponentVisible({ id:id,visible:true })
          }
        }
      }
      if (ruleQueryList.length > 0) {
        await this.queryRules(ruleQueryList)
      }
    },
    dealComponentRule (item) {
      if (!item.childRuleTag && (!item.rule || !item.rule.tag)){
        this.setComponentVisible({ id:item._id,visible:true })
        return
      } 
      if (item.rule && item.rule.onlineTime && item.rule.offlineTime) {
        let now = new Date().getTime()
        let start = new Date(item.rule.onlineTime).getTime()
        let end = new Date(item.rule.offlineTime).getTime()
        if (now >= start && now <= end) {
        // 在有效时间内，依然要调用接口，服务端验证时间有效性
          return item._id
        } else {
          this.setComponentVisible({ id:item._id,visible:false })
          return
        }
      } else {
        return item._id
      }
    },
    async queryRules (ruleQueryList) {
      let requestData={
        activityCode: this.activityCode,
        moduleCodes: ruleQueryList,
        userNo: this.userNo,
        versionDomain:this.versionRule
      }
      let res =await this.$axios.post('/v2/rule/rulesFilter', requestData).catch( () => {
        this.hideComponents(ruleQueryList)
      })
      if (res.flag === 'S') {
        this.handleQueryResults(res.data)
      } else {
        this.hideComponents(ruleQueryList)
      }
    },
    handleQueryResults (list) {
      list.forEach((item) => { 
        this.setComponentVisible({ id:item.moduleCode,visible:item.hit }) 
        this.setComponentRuleContens({ id:item.moduleCode,arr:item.results })  
      })
    },
    ddRedirect () {
      if (this.activityInfo.activityStatus !== 2) return
      if (
        this.activityInfo.ddtype &&
          this.activityInfo.ddtype === '2' &&
          this.activityInfo.ddUrlList
      ) {
        let ddList = JSON.parse(JSON.stringify(this.activityInfo.ddUrlList))
        this.checkActivityStatus(ddList)
      }
    },
    checkActivityStatus (ddUrlList) {
      if (ddUrlList.length === 0) return
      let url = ddUrlList[0].url
      let activityCode = tool.getUrlParamFromString('activityCode', url)
      if (activityCode) {
        // lego page,check lego status
        get(tool.getPageJsonUrl(activityCode)).then((response) => {
          if (response.activityStatus === 0) {
            // status is online
            tool.navigateTo(url)
          } else {
            // read next activity
            ddUrlList.splice(0, 1)
            this.checkActivityStatus(ddUrlList)
          }
        })
      } else {
        // other page
        setTimeout(function () {
          tool.navigateTo(url)
        }, 2000)
      }
    },
    scroll () {
      let scrollHeight =
        document.body.scrollTop || document.documentElement.scrollTop
      this.scrollTopHeight = scrollHeight
      if (scrollHeight > screen.height && this.activityInfo.isStick) {
        this.isShowStick = true
      } else {
        this.isShowStick = false
      }
    },
    scrollToTop () {
      document.body.scrollTo({ left: 0, top: 0, behavior: 'smooth' })
      document.documentElement.scrollTo({ left: 0, top: 0, behavior: 'smooth' })
    },
    async clientPageRender () {
      if (!tool.IS_NATIVE()) {
        this.initLoading=false
        return
      }
      let res= await tool.getLoginStatus()
      if (res){
        this.authTag = true
        this.setUserNo(res)
        await this.loadPageJson()
        return
      } else {
        this.initLoading=false
        console.log('处理返回之后又回到h5页面的逻辑')
        // window.$$.EventListener.off('back').on('back',async () => {
        //   let account = await tool.getLoginStatus()
        //   if (account) {
        //     this.authTag = true
        //     this.setUserNo(account)
        //     this.initLoading=true
        //     await this.loadPageJson()
        //     if (this.pageContent.showCouponPop){
        //       // 登录之后重新刷新弹窗
        //       this.loadRetainPopCoupon()
        //     }
        //   }
        // })
        if (!this.pageContent.unauthImage) return
        // tool.goToLogin()
        console.log('在这里要跳转到app登录页面')
      }
    },
    unAuthImageClik () {
      // tool.goToLogin()
      console.log('在这里要跳转到app登录页面')
    },
    initAndriodBack () {
      console.log('在这里处理安卓返回事件')
      // if (!tool.IS_NATIVE() || !window.App.IS_ANDROID) return
      // window.App.call('interceptBackPressEvent', {
      //   data: { intercept: 'Y' }
      // })
      // window.$$.EventListener
      //   .off('onBackPressed')
      //   .on('onBackPressed', this.handleAndriodBack)
    },
    handleAndriodBack () {
      if (!this.swipeBackTag){
        return
      }
      if (location.href.includes('/rule')) {
        this.$router.back()
      } else {
        if (this.pageContent.showCouponPop && this.userNo){
          this.handleLeavePage()
        } else {
          console.log('在这里接YUP返回事件')
          // window.App.back()
        }
      }
    }
  },

}
</script>

<style lang="less" scoped>
@import '@/assets/styles/mobile.less';
</style>
